import 'package:family_expense/features/account_user/services/user_service.dart';
import 'package:family_expense/features/account_user/widgets/user_shared.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class UpdateAccountGroupUser extends StatefulWidget {
  const UpdateAccountGroupUser(this.user, {super.key});

  final User user;

  @override
  State<UpdateAccountGroupUser> createState() => _UpdateAccountGroupUserState();
}

class _UpdateAccountGroupUserState extends State<UpdateAccountGroupUser> {
  final UserService _userService = UserService();

  late final User _user = widget.user.clone();
  late final User _initialUser = _user.clone();

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: _onPopInvokedWithResult,
      child: Scaffold(
        appBar: AppBar(title: const Text('修改信息')),
        body: _buildForm(),
      ),
    );
  }

  /// Builds the input form.
  Widget _buildForm() {
    // DO NOT PUT [Form] in [ListView]. Uses [SingleChildScrollView] instead.
    // Textfield in gallery gets reset if scrolled out of view.
    // https://github.com/flutter/flutter/issues/11500
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          const ListCaption('基本信息'),
          ListTile(
            title: const Text('用户名'),
            trailing: Text(_user.username!.formatMobilePhoneNumber()),
          ),
          ListTile(
            title: const Text('状态'),
            trailing: UserEnableChip(_user.enabled!),
          ),
          _buildDivider(),
          const ListCaption('角色设置'),
          AccountGroupUserRoleSelection(_user.fullRoles!, (selectedRoles) {
            if (mounted) {
              setState(() => _user.fullRoles = selectedRoles);
            }
          }),
          _buildDivider(),
          Container(
            margin: const EdgeInsets.only(top: 40.0),
            height: 44.0,
            child: PressStatusButton(
              onPressed: _save,
              disabledChild: const Text(
                '正在保存',
                style: TextStyle(fontSize: 20.0),
              ),
              child: const Text('保 存', style: TextStyle(fontSize: 20.0)),
            ),
          ),
        ],
      ),
    );
  }

  /// Builds divider between list tile.
  Widget _buildDivider() {
    return const SizedBox(height: 20.0);
  }

  // /// Checks the data before popping.
  void _onPopInvokedWithResult(bool didPop, dynamic result) {
    if (didPop) {
      return;
    }

    // If the page is popping up while being changed without saving then the confirm dialog will be displayed.
    if (!_initialUser.equals(_user)) {
      showConfirmDialog(
        context,
        '放弃保存？',
        onConfirm: () => NavigatorHelper.pop(context),
      );
    } else {
      // Allows to close current page.
      NavigatorHelper.pop(context);
    }
  }

  /// Saves the new [User] to server and pops.
  /// When pops notify previous page to reload.
  Future<void> _save() async {
    // Validate returns true if data is valid, or false otherwise.
    if (_user.fullRoles!.isEmpty) {
      showToast('请设置用户角色');
      return;
    }

    // Saves the new user and pops if successful.
    final success = await _userService.updateRoles(_user);

    final authStateService = AuthStateService.instance;

    // If user info exists in collection for quick login then we need to update it as well.
    if (await authStateService.isUserInCollection(_user)) {
      authStateService.saveUserToCollection(_user);
    }

    // DO NOT use BuildContext across asynchronous gaps.
    // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
    if (mounted) {
      // Pops current page and notifies the last page to update the list.
      NavigatorHelper.pop(context, success);
    }
  }
}
